<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>用户管理 | 语音增强对比平台</title>
  <link rel="stylesheet" href="/src/css/style.css">
</head>
<body>
  <nav class="navbar">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
      <a href="/" class="text-xl font-bold">语音增强对比平台</a>
      <div class="flex items-center space-x-4">
        <a href="/" class="hover:text-gray-200">返回首页</a>
        <div id="user-info" class="text-sm text-gray-200"></div>
      </div>
    </div>
  </nav>

  <main class="container">
    <section class="section card">
      <h2>用户管理</h2>
      <p class="mb-4 text-gray-700">仅管理员可访问本页，您可以查看所有用户。</p>

      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div>
          <div class="flex items-center justify-between mb-3">
            <h3 class="text-base font-semibold">所有用户</h3>
            <button id="open-create-admin" class="bg-blue-500 hover:bg-blue-600 text-white font-medium px-6 py-3 rounded-lg transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">新增管理员用户</button>
          </div>
          <div id="users-status" class="hidden mt-2 text-sm"></div>
          <div class="overflow-x-auto">
            <table class="w-full border-collapse bg-white rounded-lg shadow-sm">
              <thead>
                <tr class="bg-gray-50">
                  <th class="border border-gray-200 px-4 py-2 text-left">ID</th>
                  <th class="border border-gray-200 px-4 py-2 text-left">用户名</th>
                  <th class="border border-gray-200 px-4 py-2 text-left">角色</th>
                  <th class="border border-gray-200 px-4 py-2 text-left">创建时间</th>
                  <th class="border border-gray-200 px-4 py-2 text-left">操作</th>
                </tr>
              </thead>
              <tbody id="users-tbody"></tbody>
            </table>
          </div>
        </div>

        

        
      </div>
    </section>
  </main>

  <footer class="bg-gray-800 text-white py-6">
    <div class="container mx-auto px-4 text-center">
      <p>语音增强对比平台 &copy; 2024</p>
    </div>
  </footer>

  <!-- 新增管理员弹窗 -->
  <div id="create-admin-modal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-lg p-6 w-full max-w-md mx-4">
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-semibold">新增管理员用户</h3>
        <button id="close-create-admin" class="text-gray-500 hover:text-gray-700">&times;</button>
      </div>
      <div class="space-y-3">
        <div>
          <label class="block text-sm mb-1">用户名</label>
          <input id="ca-username" class="w-full px-3 py-2 border border-gray-300 rounded-lg" placeholder="3-20位，字母数字下划线" />
        </div>
        <div>
          <label class="block text-sm mb-1">密码</label>
          <input id="ca-password" type="password" class="w-full px-3 py-2 border border-gray-300 rounded-lg" placeholder="至少6位" />
        </div>
        <div>
          <label class="block text-sm mb-1">确认密码</label>
          <input id="ca-password2" type="password" class="w-full px-3 py-2 border border-gray-300 rounded-lg" placeholder="再次输入密码" />
        </div>
        <div class="flex space-x-3 pt-2">
          <button 
            id="submit-create-admin" 
            class="flex-1 bg-blue-500 hover:bg-blue-600 text-white font-medium px-6 py-3 rounded-lg transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
          >
            确定
          </button>
          <button 
            id="cancel-create-admin" 
            class="flex-1 bg-white text-gray-700 border border-gray-300 hover:bg-gray-50 font-medium px-6 py-3 rounded-lg transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-gray-300 focus:ring-offset-2"
          >
            取消
          </button>
        </div>
        <div id="create-admin-status" class="hidden text-sm"></div>
      </div>
    </div>
  </div>

  

  <script type="module">
    import { initAuthSystem } from '/src/js/auth.js';

    document.addEventListener('DOMContentLoaded', () => {
      const auth = initAuthSystem();
      if (auth && typeof auth.init === 'function') auth.init();

      // 若非管理员，跳回首页
      const userDataStr = localStorage.getItem('voice_community_user');
      let userData = null;
      try { userData = userDataStr ? JSON.parse(userDataStr) : null; } catch {}
      if (!userData || userData.role !== 'admin') {
        window.location.href = '/';
        return;
      }

      // 显示用户信息
      const info = document.getElementById('user-info');
      if (info) info.textContent = `管理员: ${userData.username}`;

      // 加载用户列表
      loadUsers();
    });

    async function loadUsers() {
      const status = document.getElementById('users-status');
      const tbody = document.getElementById('users-tbody');
      tbody.innerHTML = '';
      showStatus(status, '正在加载用户列表...', 'info');

      const token = getToken();
      try {
        const res = await fetch('/api/auth/users', { headers: { Authorization: `Bearer ${token}` } });
        const data = await res.json();
        if (!data.success) {
          showStatus(status, `加载失败：${data.message}`, 'error');
          return;
        }
        hideStatus(status);
        data.data.forEach(u => {
          const tr = document.createElement('tr');
          tr.innerHTML = `
            <td class="border border-gray-200 px-4 py-2">${u.id}</td>
            <td class="border border-gray-200 px-4 py-2">${u.username}</td>
            <td class="border border-gray-200 px-4 py-2">${u.role}</td>
            <td class="border border-gray-200 px-4 py-2">${new Date(u.createdAt).toLocaleString('zh-CN')}</td>
            <td class="border border-gray-200 px-4 py-2">
              <button class="text-blue-600 hover:text-blue-800 text-sm" onclick="resetPasswordPrompt('${u.id}','${u.username}')">重置密码</button>
              <span class="mx-2 text-gray-300">|</span>
              <button class="text-red-600 hover:text-red-800 text-sm" onclick="deleteUserConfirm('${u.id}','${u.username}')">删除</button>
            </td>
          `;
          tbody.appendChild(tr);
        });
      } catch (e) {
        showStatus(status, '加载失败，请检查网络', 'error');
      }
    }

    function getToken() {
      try {
        const s = localStorage.getItem('voice_community_user');
        if (!s) return null;
        const u = JSON.parse(s);
        return u.token;
      } catch { return null; }
    }

    function showStatus(el, msg, type) {
      if (!el) return;
      el.className = 'mt-2 text-sm p-2 rounded';
      el.classList.remove('hidden');
      if (type === 'error') el.className += ' bg-red-100 text-red-800 border border-red-200';
      else if (type === 'success') el.className += ' bg-green-100 text-green-800 border border-green-200';
      else el.className += ' bg-blue-100 text-blue-800 border border-blue-200';
      el.textContent = msg;
    }
    function hideStatus(el) { if (el) el.classList.add('hidden'); }

    // ===== 新增管理员弹窗逻辑 =====
    const openBtn = document.getElementById('open-create-admin');
    const openBtn2 = document.getElementById('open-create-admin-2');
    const modal = document.getElementById('create-admin-modal');
    const closeBtn = document.getElementById('close-create-admin');
    const cancelBtn = document.getElementById('cancel-create-admin');
    const submitBtn = document.getElementById('submit-create-admin');
    const statusEl = document.getElementById('create-admin-status');

    function openModal() { if (modal) { modal.classList.remove('hidden'); modal.classList.add('flex'); } }
    function closeModal() { if (modal) { modal.classList.add('hidden'); modal.classList.remove('flex'); resetModal(); } }
    function resetModal() {
      const u = document.getElementById('ca-username');
      const p1 = document.getElementById('ca-password');
      const p2 = document.getElementById('ca-password2');
      if (u) u.value = '';
      if (p1) p1.value = '';
      if (p2) p2.value = '';
      hideStatus(statusEl);
    }

    if (openBtn) openBtn.addEventListener('click', openModal);
    if (openBtn2) openBtn2.addEventListener('click', openModal);
    if (closeBtn) closeBtn.addEventListener('click', closeModal);
    if (cancelBtn) cancelBtn.addEventListener('click', closeModal);
    if (modal) modal.addEventListener('click', (e) => { if (e.target === modal) closeModal(); });

    if (submitBtn) submitBtn.addEventListener('click', async () => {
      const username = document.getElementById('ca-username').value.trim();
      const pwd = document.getElementById('ca-password').value;
      const pwd2 = document.getElementById('ca-password2').value;

      if (!/^[a-zA-Z0-9_]{3,20}$/.test(username)) { showStatus(statusEl, '用户名需为3-20位字母数字下划线', 'error'); return; }
      if (!pwd || pwd.length < 6) { showStatus(statusEl, '密码至少6位', 'error'); return; }
      if (pwd !== pwd2) { showStatus(statusEl, '两次输入的密码不一致', 'error'); return; }

      showStatus(statusEl, '正在创建...', 'info');
      const token = getToken();
      try {
        const res = await fetch('/api/auth/create-admin', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
          body: JSON.stringify({ username, password: pwd })
        });
        const data = await res.json();
        if (data.success) {
          closeModal();
          alert(`✅ 已创建管理员：${data.user.username}`);
          loadUsers();
        } else {
          showStatus(statusEl, `❌ 创建失败：${data.message || '未知错误'}`, 'error');
        }
      } catch (e) {
        showStatus(statusEl, '❌ 请求失败，请检查网络', 'error');
      }
    });


    // 提示并调用后端重置密码
    window.resetPasswordPrompt = async function(userId, username) {
      const newPwd = prompt(`为用户 ${username} 设置新密码（至少6位）：`);
      if (!newPwd) return;
      if (newPwd.length < 6) { alert('密码长度至少6位'); return; }
      const token = getToken();
      try {
        const res = await fetch(`/api/auth/users/${encodeURIComponent(userId)}/password`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
          body: JSON.stringify({ newPassword: newPwd })
        });
        const data = await res.json();
        if (data.success) {
          alert('密码已更新');
        } else {
          alert(`更新失败：${data.message || '未知错误'}`);
        }
      } catch (e) {
        alert('请求失败，请检查网络');
      }
    }

    // 确认并调用后端删除用户
    window.deleteUserConfirm = async function(userId, username) {
      if (!confirm(`确定删除管理员 ${username} 吗？`)) return;
      const token = getToken();
      try {
        const res = await fetch(`/api/auth/users/${encodeURIComponent(userId)}`, {
          method: 'DELETE',
          headers: { Authorization: `Bearer ${token}` }
        });
        const data = await res.json();
        if (data.success) {
          alert('已删除');
          loadUsers();
        } else {
          alert(`删除失败：${data.message || '未知错误'}`);
        }
      } catch (e) {
        alert('请求失败，请检查网络');
      }
    }
  </script>
</body>
</html>

